package com.atguigu.yygh.order.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.enums.RefundStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.RefundInfoService;
import com.atguigu.yygh.order.service.WeixinService;
import com.atguigu.yygh.order.utils.ConstantPropertiesUtils;
import com.atguigu.yygh.order.utils.HttpClient;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author:ahang
 * @create:2022-09-16 8:36
 * @Description:
 */
@Service
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RefundInfoService refundInfoService;

    //生成支付连接
    @Override
    public Map createNative(Long orderId) {
        //1.从redis中根据订单找到map（链接+其他参数）五分钟之内使用的是同一个链接
        Map map = (Map) redisTemplate.opsForValue().get(orderId.toString());
        if(map != null){
            return map;
        }
        //2.根据订单id查询订单对象
        OrderInfo orderInfo = orderInfoService.getOrderInfo(orderId);
        if(orderInfo == null){
            throw new YyghException(20001,"订单不存在");
        }
        //3.为订单创建支付记录（如果有支付记录则不创建）
        paymentService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());

        //4.调用微信"统一下单"接口
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("appid", ConstantPropertiesUtils.APPID);//公众账号ID
        paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);//商户号
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串	32位以内
        Date reserveDate = orderInfo.getReserveDate();//安排日期(就诊日期，出诊日期)
        String reserveDateString = new DateTime(reserveDate).toString("yyyy/MM/dd");
        String body = reserveDateString + "就诊"+ orderInfo.getDepname(); // 2022/07/17 就诊 多发性硬化专科门诊
        paramMap.put("body", body);//商品描述
        paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
        //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
        paramMap.put("total_fee", "1");//订单总金额。测试1分钱
        paramMap.put("spbill_create_ip", "127.0.0.1");//终端ip=测试
        paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");//没有
        paramMap.put("trade_type", "NATIVE");//扫码支付，必须写成NATIVE

        try {
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            httpClient.setHttps(true);//支付https协议
            String xmlParam = WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY);
            httpClient.setXmlParam(xmlParam);//设置参数（微信支付端的接口需要xml格式的参数）
            httpClient.post();//post请求

            //5.参数封装 + 发送请求 + 返回值 + 解析返回值
            String xmlContent = httpClient.getContent();//xml 类型的返回值
            Map<String, String> responseMap = WXPayUtil.xmlToMap(xmlContent);//xml转化为map

            Map<String,Object> result = new HashMap<>();
            result.put("orderId",orderId);
            result.put("totalFee",orderInfo.getAmount());
            result.put("codeUrl",responseMap.get("code_url"));
            result.put("resultCode",responseMap.get("result_code"));

            //存入redis5分钟
            redisTemplate.opsForValue().set(orderId.toString(),result,5, TimeUnit.MINUTES);

            return result;


        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 根据订单号查询订单状态 调用微信的状态查询接口
     * @param orderId
     * @return
     */
    @Override
    public Map queryPayStatus(Long orderId) {
        //1.根据订单号查询订单
        OrderInfo orderInfo = orderInfoService.getOrderInfo(orderId);
        //2.封装请求参数
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("appid",ConstantPropertiesUtils.APPID);
        paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);
        paramMap.put("out_trade_no",orderInfo.getOutTradeNo());
        paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
        //3.发请求（参数和返回值都是xml格式）
        try {
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            httpClient.setHttps(true);
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
            httpClient.post();

            //4.解析返回值
            String xmlContent = httpClient.getContent();
            Map<String, String> result = WXPayUtil.xmlToMap(xmlContent);

            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 退款
     * @param orderId
     * @return
     */
    @Override
    public Boolean refund(Long orderId) {
        //1.查询支付记录
        PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());
        //2.根据支付记录创建退款记录
        RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
        //3.判断退款状态,如果已经退款 返回true
        if(refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()){
            return true;
        }
        //4.调用退款接口
        Map<String,String> map = new HashMap<>();
        map.put("appid",ConstantPropertiesUtils.APPID); //公众账号ID
        map.put("mch_id",ConstantPropertiesUtils.PARTNER); //商户编号
        map.put("nonce_str",WXPayUtil.generateNonceStr()); //随机字符串
        map.put("transaction_id",paymentInfo.getTradeNo()); //支付成功后的流水号
        map.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
        map.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
        map.put("total_fee","1");//订单金额
        map.put("refund_fee","1");//退款金额

        try {
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            httpClient.setHttps(true);
            httpClient.setCert(true);
            httpClient.setCertPassword(ConstantPropertiesUtils.PARTNER);
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(map,ConstantPropertiesUtils.PARTNERKEY));
            httpClient.post();

            //5.解析返回值
            String xmlContent = httpClient.getContent();
            Map<String, String> result = WXPayUtil.xmlToMap(xmlContent);
            //6.如果退款成功,更新退款记录
            if(result != null && result.get("result_code").equalsIgnoreCase(WXPayConstants.SUCCESS)){
                refundInfo.setTradeNo(result.get("transaction_id"));//退款成功后的流水号
                refundInfo.setCallbackTime(new Date());
                refundInfo.setCallbackContent(result.toString());
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());//2
                refundInfo.setUpdateTime(new Date());
                refundInfoService.updateById(refundInfo);
            }


        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
